package com.ruoyi.common.utils.mail;

import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Objects;

/**
 * @author: yinjc
 * @Date: 2022-09-28
 * @Description: 邮件服务
 */
@Slf4j
@Component
public class MailUtils {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private MailProperties mailProperties;

    public void sendSimpleMail(String subject, String body) {
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setFrom(mailProperties.getFrom());
            mailMessage.setTo(mailProperties.getTo());
            mailMessage.setSubject(subject);
            mailMessage.setText(body);
            javaMailSender.send(mailMessage);
        } catch (Exception e) {
            log.error("邮件发送失败，失败信息为：" + e.getMessage());
        }
    }

    public void sendHtmlMail(String subject, String body, Map<String, String> attachmentMap) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            //是否发送的邮件是富文本（附件，图片，html等）
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(mailProperties.getFrom());
            mimeMessageHelper.setTo(mailProperties.getTo());
            mimeMessageHelper.setSubject(subject);
            //重点，默认为false，显示原始html代码，无效果
            mimeMessageHelper.setText(body, true);

            if(attachmentMap != null){
                attachmentMap.entrySet().stream().forEach(entrySet -> {
                    File file = new File(entrySet.getValue());
                    if(file.exists()){
                        try {
                            mimeMessageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));
                        } catch (MessagingException e) {
                            log.error("添加附件失败，失败信息为：" + e.getMessage());
                        }
                    }
                });
            }
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("邮件发送失败，失败信息为：" + e.getMessage());
        }
    }

    /**
     * 发送带图片资源的邮件
      * @param subject 主题
     * @param body 邮件内容
     * @param srcPath 图片资源路径
     * @param resIds 图片资源编号
     */
    public void sendMailWithImage(String subject, String body, String[] srcPath, String[] resIds) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(mailProperties.getFrom());
            mimeMessageHelper.setTo(mailProperties.getTo());
            mimeMessageHelper.setSubject(subject);
            //第二个参数true表示邮件正文是HTML格式的，该参数不传默认为false。
            mimeMessageHelper.setText(body, true);
            for (int i = 0; i < srcPath.length; i++) {
                //通过FileSystemResource构造静态资源
                FileSystemResource res = new FileSystemResource(new File(srcPath[i]));
                //调用addInline方法将资源加入邮件对象中
                mimeMessageHelper.addInline(resIds[i], res);
            }
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("邮件发送失败，失败信息为：" + e.getMessage());
        }
    }

    public void sendTemplateMail(String subject, String content, String[] srcPath, String[] resIds, Map<String, String> attachmentMap) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(mailProperties.getFrom());
            mimeMessageHelper.setTo(mailProperties.getTo());
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content, true);

            if (null != attachmentMap ) {
                attachmentMap.entrySet().stream().forEach(entrySet -> {
                    File file = new File(entrySet.getValue());
                    if(file.exists()){
                        try {
                            mimeMessageHelper.addAttachment(
                                    Objects.requireNonNull(entrySet.getKey()), //附件名称
                                    new FileSystemResource(file), //附件流
                                    Files.probeContentType(Paths.get(Objects.requireNonNull(entrySet.getKey())))//附件类型
                            );
                        } catch (MessagingException e) {
                            log.error("添加附件失败，失败信息为：" + e.getMessage());
                        } catch (IOException e) {
                            log.error("添加附件失败，失败信息为：" + e.getMessage());
                        }
                    }
                });
            }

            if (srcPath.length > 0 && resIds.length > 0 && srcPath.length == resIds.length) {
                for (int i = 0; i < srcPath.length; i++) {
                    //通过FileSystemResource构造静态资源
                    FileSystemResource res = new FileSystemResource(new File(srcPath[i]));
                    //调用addInline方法将资源加入邮件对象中
                    mimeMessageHelper.addInline(resIds[i], res);
                }
            }
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            log.error("邮件发送失败，失败信息为：" + e.getMessage());
        }
    }

}
